import requests,yaml,os,json
from jinja2 import FileSystemLoader,Environment
import pandas as pd
def loadConfig():
    """
    加载配置信息
    """
    with open('config/app.yml','r',encoding='utf-8') as f:
        config = yaml.load(f,Loader=yaml.FullLoader)
    return config
def loadYamlUsecase(config):
    """
    加载yaml用例
    """
    res = []
    dir = config['usecaseDir']
    for root,dirs,files in os.walk(dir):
        for file in files:
            if os.path.splitext(file)[1] in ['.yaml','.yml']:
                with open(os.path.join(root,file),'r',encoding="utf-8") as f:
                    config = yaml.load(f,Loader=yaml.FullLoader)
                    usecaseList = config['usecaseList']
                    for item in usecaseList:
                        res.append(item)
    return res
def loadXlsxUsecase(config):
    """
    加载excel用例
    """
    res = []
    dir = config['usecaseDir']
    for root,dirs,files in os.walk(dir):
        for file in files:
            if os.path.splitext(file)[1] in ['.xlsx']:
                df = pd.read_excel(os.path.join(root,file))
                data = df.to_dict('records')
                for item in data:
                    res.append(item)
    return res
def processUsecase(usecase,config):
    """
    执行测试用例-单个
    """
    res = usecase
    headers = {"Content-Type": usecase["contentType"]}
    baseUrl = config['baseUrl']
    url = usecase['url']
    if url.startswith('http') == False:
        url = baseUrl+url
    data = usecase['data']
    r = requests.post(url,data=data,headers=headers)
    body = r.text
    print(f"请求地址：{r.url}")
    print(f"请求头：{r.headers}")
    print(f"请求体：{r.request.body}")
    print(f"响应时间：{r.elapsed.total_seconds()}s")
    print(f"返回结果：{r.text}")
    bodyJson = json.loads(body)
    res['result']=bodyJson['code'] == usecase['expectedResult']
    res['body']=body
    res['totalSeconds']=r.elapsed.total_seconds()
    return res
def processUsecaseList(usecaseList,config):
    """
    执行测试用例-遍历
    """
    res = []
    for usecase in usecaseList:
        res.append(processUsecase(usecase,config))
    return res
def buildTestReport(data,config):
    """
    生成测试报告
    """
    env = Environment(loader=FileSystemLoader('templates'))
    template = env.get_template('index.html')
    html = template.render({
        "data": reportData
    })
    with open(config['testreport']+"/result.html", 'w',encoding="utf-8") as f:
        f.write(html)
    return 1
if __name__ == '__main__':
    config = loadConfig()
    usecaseType = config['usecaseType']
    usecaseList = []
    if usecaseType == 'yaml':
        usecaseList = loadYamlUsecase(config)
    elif usecaseType == 'xlsx':
        usecaseList = loadXlsxUsecase(config)
    else:
        print("用例不存在或不支持此类型")
    if len(usecaseList) == 0:
        print("用例不存在")
    else:
        reportData = processUsecaseList(usecaseList,config)
        buildTestReport(reportData,config)